﻿using HtmlAgilityPack;
using King.Api.Models.Dto;
using King.Helper;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using Serilog;
using System;
using System.Threading.Tasks;

namespace King.Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DeviceController : ControllerBase
    {
        private ICacheService _cache;

        public DeviceController(ICacheService cache)
        {
            _cache = cache;
        }

        /// <summary>
        /// 获取设备数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]

        public async Task<DeviceDto> GetData()
        {

            //string url = "http://124.70.74.79:18080/";
            //HtmlWeb web = new HtmlWeb();        
            //HtmlDocument html = await web.LoadFromWebAsync(htmlData);
            if (!_cache.Exists(Common.DeviceData))
            {
                return new DeviceDto();
            }

            //var htmlData = _cache.Get<string>(Common.DeviceData);
            //HtmlDocument html = new HtmlDocument();
            //html.LoadHtml(htmlData);
            //var jsonStr = html.DocumentNode.SelectSingleNode("//p").InnerText;

            var jsonStr = _cache.Get<string>(Common.DeviceData);

            JObject jsonData = JObject.Parse(jsonStr);

            var jsonObj = jsonData["params"];

            #region 生产信息
            var production = new ProductionDto()
            {
                current_team = EnumHelper.GetDescription((TeamInfo)Convert.ToInt32(jsonObj["current_team"])),
                product_type = EnumHelper.GetDescription((ProductType)Convert.ToInt32(jsonObj["product_type"])),
                plan_num = Convert.ToInt32(jsonObj["plan_num"]),
                current_team_num = Convert.ToInt32(jsonObj["current_team_num"]),
                all_team_num = Convert.ToInt32(jsonObj["all_team_num"]),
                surplus_num = Convert.ToInt32(jsonObj["surplus_num"]),
                num_modify = Convert.ToInt32(jsonObj["num_modify"]),
                last_production_time = Convert.ToInt32(jsonObj["last_production_time"]),
                now_production_time = Convert.ToInt32(jsonObj["now_production_time"]),
                box_countdown_set = Convert.ToInt32(jsonObj["box_countdown_set"]),
            };
            #endregion

            #region 驱动、油泵、液压、散热信息
            var driveMonitoring = new DriveMonitoringDto()
            {
                mreciprod_controlmodel = Convert.ToInt32(jsonObj["mreciprod_controlmodel"]),
                mreciprod_axisenable = jsonObj["mreciprod_axisenable"].ToString().Equals("1") ? true : false,
                mreciprod_positiveinch = jsonObj["mreciprod_positiveinch"].ToString().Equals("1") ? true : false,
                mreciprod_reverseinch = jsonObj["mreciprod_reverseinch"].ToString().Equals("1") ? true : false,
                mreciprod_faultclear = jsonObj["mreciprod_faultclear"].ToString().Equals("1") ? true : false,
                mreciprod_speedinch = Convert.ToInt32(jsonObj["mreciprod_speedinch"]),
                mreciprod_targetlocation = Convert.ToInt32(jsonObj["mreciprod_targetlocation"]),
                mreciprod_targetspeed = Convert.ToInt32(jsonObj["mreciprod_targetspeed"]),
                mreciprod_trig0return = jsonObj["mreciprod_trig0return"].ToString().Equals("1") ? true : false,
                mreciprod_fixreturn = jsonObj["mreciprod_fixreturn"].ToString().Equals("1") ? true : false,
                mreciprod_axisstop = jsonObj["mreciprod_axisstop"].ToString().Equals("1") ? true : false,
                mreciprod_manullocation = Convert.ToInt32(jsonObj["mreciprod_manullocation"]),
                mreciprod_manulspeed = Convert.ToInt32(jsonObj["mreciprod_manulspeed"]),
                mreciprod_autopulse = Convert.ToInt32(jsonObj["mreciprod_autopulse"]),
                mreciprod_autospeed = Convert.ToInt32(jsonObj["mreciprod_autospeed"]),
                mreciprod_servoready = jsonObj["mreciprod_servoready"].ToString().Equals("1") ? true : false,
                mreciprod_locationstand = jsonObj["mreciprod_locationstand"].ToString().Equals("1") ? true : false,
                mreciprod_speedstand = jsonObj["mreciprod_speedstand"].ToString().Equals("1") ? true : false,
                mreciprod_0stand = jsonObj["mreciprod_0stand"].ToString().Equals("1") ? true : false,
                mreciprod_servorerror = jsonObj["mreciprod_servorerror"].ToString().Equals("1") ? true : false,
                mreciprod_errorbandrelease = jsonObj["mreciprod_errorbandrelease"].ToString().Equals("1") ? true : false,
                mreciprod_now_location = Convert.ToInt32(jsonObj["mreciprod_now_location"]),
                mreciprod_now_speed = Convert.ToInt32(jsonObj["mreciprod_now_speed"]),
                mreciprod_now_torque = Convert.ToDouble(jsonObj["mreciprod_now_torque"]),
                mreciprod_now_load = Convert.ToDouble(jsonObj["mreciprod_now_load"]),
                mreciprod_drivefault = Convert.ToInt32(jsonObj["mreciprod_drivefault"])
            };


            var oilPump = new OilPumpDto()
            {
                hydraulicstation_motot1_power = jsonObj["hydraulicstation_motot1_power"].ToString().Equals("1") ? true : false,
                hydraulicstation_motot1_work = jsonObj["hydraulicstation_motot1_work"].ToString().Equals("1") ? true : false,
                hydraulicstation_motot2_power = jsonObj["hydraulicstation_motot2_power"].ToString().Equals("1") ? true : false,
                hydraulicstation_motot2_work = jsonObj["hydraulicstation_motot2_work"].ToString().Equals("1") ? true : false,
            };

            var hydraulicStation = new HydraulicStationDto()
            {
                hydraulicstation1_temp_uplimit = jsonObj["hydraulicstation1_temp_uplimit"].ToString().Equals("1") ? true : false,
                hydraulicstation1_temp_lowerlimit = jsonObj["hydraulicstation1_temp_lowerlimit"].ToString().Equals("1") ? true : false,
                hydraulicstation1_press_uplimit = jsonObj["hydraulicstation1_press_uplimit"].ToString().Equals("1") ? true : false,
                hydraulicstation1_press_lowerlimit = jsonObj["hydraulicstation1_press_lowerlimit"].ToString().Equals("1") ? true : false,
                hydraulicstation1_level_lowerlimit = jsonObj["hydraulicstation1_level_lowerlimit"].ToString().Equals("1") ? true : false,
                hydraulicstation1_return_block1 = jsonObj["hydraulicstation1_return_block1"].ToString().Equals("1") ? true : false,
                hydraulicstation1_return_block2 = jsonObj["hydraulicstation1_return_block2"].ToString().Equals("1") ? true : false,
                hydraulicstation1_absorption_block1 = jsonObj["hydraulicstation1_absorption_block1"].ToString().Equals("1") ? true : false,
                hydraulicstation1_absorption_block2 = jsonObj["hydraulicstation1_absorption_block2"].ToString().Equals("1") ? true : false,
            };

            var heatDissipationSystem = new HeatDissipationSystemDto()
            {
                hydraulicstation1_cool_power = jsonObj["hydraulicstation1_cool_power"].ToString().Equals("1") ? true : false,
                hydraulicstation1_cool_work = jsonObj["hydraulicstation1_cool_work"].ToString().Equals("1") ? true : false,
                hydraulicstation1_cool_mode = jsonObj["hydraulicstation1_cool_mode"].ToString().Equals("1") ? true : false,
            };


            var openInfoDto = new OpenInfoDto()
            {
                DriveMonitoring = driveMonitoring,
                OilPump = oilPump,
                HydraulicStation = hydraulicStation,
                HeatDissipationSystem = heatDissipationSystem
            };

            #endregion

            #region 主线工位设备 

            var station = new StationDto()
            {
                underframe_transitiontable = new underframe_transitiontable()
                {
                    c_underframe_transitiontable = jsonObj["c_underframe_transitiontable"].ToString().Equals("1") ? true : false,
                    e_underframe_transition_table = jsonObj["e_underframe_transition_table"].ToString().Equals("1") ? true : false,
                    i_underframe_transitiontable = jsonObj["i_underframe_transitiontable"].ToString().Equals("1") ? true : false,
                },
                general_assembly_platform1 = new general_assembly_platform1()
                {
                    c_general_assembly_platform1 = jsonObj["c_general_assembly_platform1"].ToString().Equals("1") ? true : false,
                    e_general_assembly_platform1 = jsonObj["e_general_assembly_platform1"].ToString().Equals("1") ? true : false,
                    i_general_assembly_platform1 = jsonObj["i_general_assembly_platform1"].ToString().Equals("1") ? true : false,
                },
                weld_inrobotbox = new weld_inrobotbox()
                {
                    c_weld_inrobotbox = jsonObj["c_weld_inrobotbox"].ToString().Equals("1") ? true : false,
                    e_weld_inrobotbox = jsonObj["e_weld_inrobotbox"].ToString().Equals("1") ? true : false,
                    i_weld_inrobotbox = jsonObj["i_weld_inrobotbox"].ToString().Equals("1") ? true : false,
                },
                general_assembly_platform2 = new general_assembly_platform2()
                {
                    c_general_assembly_platform2 = jsonObj["c_general_assembly_platform2"].ToString().Equals("1") ? true : false,
                    e_general_assembly_platform2 = jsonObj["e_general_assembly_platform2"].ToString().Equals("1") ? true : false,
                },
                weld_flower = new weld_flower()
                {
                    e_weld_flower = jsonObj["e_weld_flower"].ToString().Equals("1") ? true : false,
                    weld_flower_info = new weld_flower_info()
                    {
                        i_weld_flower_hangbasket = jsonObj["i_weld_flower_hangbasket"].ToString().Equals("1") ? true : false,
                        i_weld_flower_stationplatform = jsonObj["i_weld_flower_stationplatform"].ToString().Equals("1") ? true : false,
                        i_weld_flower_reboot = jsonObj["i_weld_flower_reboot"].ToString().Equals("1") ? true : false,
                    }
                },
                weld_vertical = new weld_vertical()
                {
                    c_weld_vertical = jsonObj["c_weld_vertical"].ToString().Equals("1") ? true : false,
                    e_weld_vertical = jsonObj["e_weld_vertical"].ToString().Equals("1") ? true : false,
                    i_weld_vertical = jsonObj["i_weld_vertical"].ToString().Equals("1") ? true : false,
                },
                top_plate_assembly = new top_plate_assembly()
                {
                    c_top_plate_assembly = jsonObj["c_top_plate_assembly"].ToString().Equals("1") ? true : false,
                    e_top_plate_assembly = jsonObj["e_top_plate_assembly"].ToString().Equals("1") ? true : false,
                    i_top_plate_assembly = jsonObj["i_top_plate_assembly"].ToString().Equals("1") ? true : false,
                },
                weld_longitud = new weld_longitud()
                {
                    e_weld_longitud = jsonObj["e_weld_longitud"].ToString().Equals("1") ? true : false,
                    i_weld_longitud = jsonObj["i_weld_longitud"].ToString().Equals("1") ? true : false,
                },
                weld_transverse = new weld_transverse()
                {
                    e_weld_transverse = jsonObj["e_weld_transverse"].ToString().Equals("1") ? true : false,
                    i_weld_transverse = jsonObj["i_weld_transverse"].ToString().Equals("1") ? true : false,
                },
                weld_downwave = new weld_downwave()
                {
                    c_weld_downwave = jsonObj["c_weld_downwave"].ToString().Equals("1") ? true : false,
                    e_weld_downwave = jsonObj["e_weld_downwave"].ToString().Equals("1") ? true : false,
                    weld_downwave_info = new weld_downwave_info()
                    {
                        i_weld_downwave2 = jsonObj["i_weld_downwave2"].ToString().Equals("1") ? true : false,
                        i_weld_downwave3 = jsonObj["i_weld_downwave3"].ToString().Equals("1") ? true : false,
                        i_weld_downwave4 = jsonObj["i_weld_downwave4"].ToString().Equals("1") ? true : false,
                    }
                },
                reboot = new reboot()
                {
                    reboot_info = new reboot_info()
                    {
                        i_reboot_botstiffener = jsonObj["i_reboot_botstiffener"].ToString().Equals("1") ? true : false,
                        i_reboot_topstiffener = jsonObj["i_reboot_topstiffener"].ToString().Equals("1") ? true : false,
                        i_reboot_overstiffener = jsonObj["i_reboot_overstiffener"].ToString().Equals("1") ? true : false
                    }
                },
                outlet = new outlet()
                {
                    c_outlet = jsonObj["c_outlet"].ToString().Equals("1") ? true : false,
                    e_outlet = jsonObj["e_outlet"].ToString().Equals("1") ? true : false,
                    i_outlet = jsonObj["i_outlet"].ToString().Equals("1") ? true : false,
                }
            };


            #endregion

            DeviceDto dto = new DeviceDto()
            {
                OpenInfo = openInfoDto,
                Production = production,
                Station = station
            };

            return dto;
        }

        /// <summary>
        /// 推送数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> PushData([FromForm] string data)
        {
            try
            {
                Log.Information("接收推送数据：" + data);
                if (_cache.Exists(Common.DeviceData))
                {
                    _cache.Replace(Common.DeviceData, data);
                }
                else
                {
                    _cache.Add(Common.DeviceData, data);
                }
                return Ok("success");
            }
            catch
            {
                return Ok("error");
            }
        }
    }


}
